<template>
  <div class="product-form">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <h2>{{ isEdit ? '编辑商品' : '新增商品' }}</h2>
      </div>
      <div class="header-right">
        <el-button @click="goBack">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </div>
    </div>

    <div class="form-content">
      <el-form
        ref="productForm"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="product-form-container"
      >
        <!-- 基本信息 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品名称" prop="name">
                <el-input
                  v-model="formData.name"
                  placeholder="请输入商品名称"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品编码" prop="code">
                <el-input
                  v-model="formData.code"
                  placeholder="请输入商品编码"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品分类" prop="categoryId">
                <el-select
                  v-model="formData.categoryId"
                  placeholder="请选择商品分类"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="category in categories"
                    :key="category.id"
                    :label="category.name"
                    :value="category.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="品牌" prop="brand">
                <el-input
                  v-model="formData.brand"
                  placeholder="请输入品牌"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="规格" prop="specification">
                <el-input
                  v-model="formData.specification"
                  placeholder="请输入规格"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位" prop="unit">
                <el-select
                  v-model="formData.unit"
                  placeholder="请选择单位"
                  style="width: 100%"
                  clearable
                >
                  <el-option label="个" value="个" />
                  <el-option label="件" value="件" />
                  <el-option label="包" value="包" />
                  <el-option label="袋" value="袋" />
                  <el-option label="瓶" value="瓶" />
                  <el-option label="盒" value="盒" />
                  <el-option label="箱" value="箱" />
                  <el-option label="千克" value="千克" />
                  <el-option label="克" value="克" />
                  <el-option label="升" value="升" />
                  <el-option label="毫升" value="毫升" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="商品描述" prop="description">
                <el-input
                  v-model="formData.description"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入商品描述"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 价格信息 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>价格信息</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="零售价" prop="retailPrice">
                <el-input-number
                  v-model="formData.retailPrice"
                  :precision="2"
                  :step="0.01"
                  :min="0"
                  style="width: 100%"
                  placeholder="零售价"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="批发价" prop="wholesalePrice">
                <el-input-number
                  v-model="formData.wholesalePrice"
                  :precision="2"
                  :step="0.01"
                  :min="0"
                  style="width: 100%"
                  placeholder="批发价"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="成本价" prop="costPrice">
                <el-input-number
                  v-model="formData.costPrice"
                  :precision="2"
                  :step="0.01"
                  :min="0"
                  style="width: 100%"
                  placeholder="成本价"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 库存信息 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>库存信息</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="初始库存" prop="initialStock">
                <el-input-number
                  v-model="formData.initialStock"
                  :min="0"
                  style="width: 100%"
                  placeholder="初始库存"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="预警库存" prop="warningStock">
                <el-input-number
                  v-model="formData.warningStock"
                  :min="0"
                  style="width: 100%"
                  placeholder="预警库存"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="最大库存" prop="maxStock">
                <el-input-number
                  v-model="formData.maxStock"
                  :min="0"
                  style="width: 100%"
                  placeholder="最大库存"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 供应商信息 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>供应商信息</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierId">
                <el-select
                  v-model="formData.supplierId"
                  placeholder="请选择供应商"
                  style="width: 100%"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="supplier in suppliers"
                    :key="supplier.id"
                    :label="supplier.name"
                    :value="supplier.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商编码" prop="supplierCode">
                <el-input
                  v-model="formData.supplierCode"
                  placeholder="请输入供应商编码"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 生产信息 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>生产信息</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="生产日期" prop="productionDate">
                <el-date-picker
                  v-model="formData.productionDate"
                  type="date"
                  placeholder="选择生产日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="保质期" prop="expiryDate">
                <el-date-picker
                  v-model="formData.expiryDate"
                  type="date"
                  placeholder="选择保质期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="生产批次" prop="batchNumber">
                <el-input
                  v-model="formData.batchNumber"
                  placeholder="请输入生产批次"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生产许可证" prop="productionLicense">
                <el-input
                  v-model="formData.productionLicense"
                  placeholder="请输入生产许可证号"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 其他信息 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>其他信息</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品状态" prop="status">
                <el-radio-group v-model="formData.status">
                  <el-radio :label="1">上架</el-radio>
                  <el-radio :label="0">下架</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否推荐" prop="isRecommend">
                <el-switch
                  v-model="formData.isRecommend"
                  active-text="是"
                  inactive-text="否"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="排序" prop="sort">
                <el-input-number
                  v-model="formData.sort"
                  :min="0"
                  :max="999"
                  style="width: 100%"
                  placeholder="排序值"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="重量(kg)" prop="weight">
                <el-input-number
                  v-model="formData.weight"
                  :precision="2"
                  :step="0.01"
                  :min="0"
                  style="width: 100%"
                  placeholder="商品重量"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'

export default defineComponent({
  name: 'ProductForm',
  components: {
    ArrowLeft
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const productForm = ref(null)
    const submitLoading = ref(false)
    
    // 判断是否为编辑模式
    const isEdit = computed(() => {
      return !!route.params.id
    })
    
    // 表单数据
    const formData = reactive({
      id: null,
      name: '',
      code: '',
      categoryId: null,
      brand: '',
      specification: '',
      unit: '',
      description: '',
      retailPrice: null,
      wholesalePrice: null,
      costPrice: null,
      initialStock: 0,
      warningStock: 0,
      maxStock: 0,
      supplierId: null,
      supplierCode: '',
      productionDate: '',
      expiryDate: '',
      batchNumber: '',
      productionLicense: '',
      status: 1,
      isRecommend: false,
      sort: 0,
      weight: null
    })
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 100, message: '商品名称长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入商品编码', trigger: 'blur' },
        { pattern: /^[A-Z0-9_-]+$/, message: '商品编码只能包含大写字母、数字、下划线和横线', trigger: 'blur' }
      ],
      categoryId: [
        { required: true, message: '请选择商品分类', trigger: 'change' }
      ],
      brand: [
        { required: true, message: '请输入品牌', trigger: 'blur' }
      ],
      specification: [
        { required: true, message: '请输入规格', trigger: 'blur' }
      ],
      unit: [
        { required: true, message: '请选择单位', trigger: 'change' }
      ],
      retailPrice: [
        { required: true, message: '请输入零售价', trigger: 'blur' },
        { type: 'number', min: 0, message: '零售价必须大于0', trigger: 'blur' }
      ],
      wholesalePrice: [
        { required: true, message: '请输入批发价', trigger: 'blur' },
        { type: 'number', min: 0, message: '批发价必须大于0', trigger: 'blur' }
      ],
      costPrice: [
        { required: true, message: '请输入成本价', trigger: 'blur' },
        { type: 'number', min: 0, message: '成本价必须大于0', trigger: 'blur' }
      ],
      supplierId: [
        { required: true, message: '请选择供应商', trigger: 'change' }
      ],
      productionDate: [
        { required: true, message: '请选择生产日期', trigger: 'change' }
      ],
      expiryDate: [
        { required: true, message: '请选择保质期', trigger: 'change' }
      ]
    }
    
    // 模拟分类数据
    const categories = ref([
      { id: 1, name: '食品饮料' },
      { id: 2, name: '生鲜果蔬' },
      { id: 3, name: '零食糖果' },
      { id: 4, name: '日用品' },
      { id: 5, name: '清洁用品' }
    ])
    
    // 模拟供应商数据
    const suppliers = ref([
      { id: 1, name: '绿色农场供应商' },
      { id: 2, name: '优质食品供应商' },
      { id: 3, name: '新鲜果蔬供应商' },
      { id: 4, name: '日用品供应商' }
    ])
    
    // 加载商品详情（编辑模式）
    const loadProductDetail = async () => {
      if (!isEdit.value) return
      
      try {
        // 模拟API请求
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 模拟编辑数据
        Object.assign(formData, {
          id: route.params.id,
          name: '有机苹果',
          code: 'P001',
          categoryId: 2,
          brand: '绿色农场',
          specification: '500g/袋',
          unit: '袋',
          description: '新鲜有机苹果，无农药残留，口感脆甜，营养丰富。',
          retailPrice: 15.80,
          wholesalePrice: 12.50,
          costPrice: 8.20,
          initialStock: 1000,
          warningStock: 100,
          maxStock: 2000,
          supplierId: 1,
          supplierCode: 'GF001',
          productionDate: '2024-01-10',
          expiryDate: '2024-02-10',
          batchNumber: '20240110-001',
          productionLicense: 'SC101234567890',
          status: 1,
          isRecommend: true,
          sort: 1,
          weight: 0.5
        })
      } catch (error) {
        console.error('加载商品详情失败:', error)
        ElMessage.error('加载商品详情失败')
      }
    }
    
    // 提交表单
    const handleSubmit = async () => {
      try {
        await productForm.value.validate()
        submitLoading.value = true
        
        // 模拟提交请求
        await new Promise(resolve => setTimeout(resolve, 2000))
        
        ElMessage.success(isEdit.value ? '商品更新成功' : '商品添加成功')
        router.push('/products/list')
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败，请检查输入信息')
      } finally {
        submitLoading.value = false
      }
    }
    
    // 返回上一页
    const goBack = () => {
      router.go(-1)
    }
    
    onMounted(() => {
      loadProductDetail()
    })
    
    return {
      isEdit,
      productForm,
      formData,
      rules,
      categories,
      suppliers,
      submitLoading,
      loadProductDetail,
      handleSubmit,
      goBack
    }
  }
})
</script>

<style scoped>
.product-form {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0;
  color: #2563eb;
}

.form-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  color: #2563eb;
}

.product-form-container {
  max-width: 1200px;
  margin: 0 auto;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-right {
    width: 100%;
    display: flex;
    gap: 10px;
  }
  
  .form-content {
    padding: 10px;
  }
}
</style> 